package com.sunxueqi.framework.security.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.sunxueqi.common.constant.CfnConstants;
import com.sunxueqi.framework.redis.RedisCacheService;
import com.sunxueqi.framework.security.LoginUser;

@Component
public class LoginService {

	@Autowired
	private TokenService tokenService;
	
	@Autowired
	private RedisCacheService redisCacheService;
	
	@Resource
    private AuthenticationManager authenticationManager;
	
	/**
	 * 登录逻辑处理
	 * @param username
	 * @param password
	 * @param code
	 * @param uuid
	 * @return
	 */
	public String login(String username, String password, String code, String uuid) {

		String verifyKey = CfnConstants.CAPTCHA_CODE_KEY + uuid;
		// 从缓存中读取登录验证码
		String captcha = redisCacheService.getCacheObject(verifyKey);
		// 将缓存中的验证码删掉
		redisCacheService.deleteObject(verifyKey);
		
		Authentication authentication = null;
		
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
        }
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		return tokenService.createToken(loginUser);
	}
}
